package com.alvin.abp.domain.editor;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**   
 * Editor for converting date type.
 * @author <a href="mailto:rex2.mj@gmail.com">Leo Meng</a>
 * @date $Date: Apr 23, 2012  $
 */
public class DateEditor extends PropertyEditorSupport {
	
	@Override
	public String getAsText() {
		String format = "yyyy-MM-dd";
		DateFormat df = new SimpleDateFormat(format);
		
		if(this.getValue() != null) {
			return df.format(this.getValue());
		}else {
			return "";
		}
	}

	@Override
	public void setAsText(String dateStr) throws IllegalArgumentException {
		Date d = this.parseToDate(dateStr);
		this.setValue(d);
	}

	private Date parseToDate(String date) {
		String format = "yyyy-MM-dd";
		DateFormat df = new SimpleDateFormat(format);
		
		if("".equals(date)){
			return null;
		}
		
		Date d = null;
		try {
			d = df.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return d;
	}
}
